package com.hao.tool.util.module.file.controller;

import cn.hutool.core.io.FileUtil;
import com.hao.tool.common.constant.Commons;
import com.hao.tool.util.component.properties.PropertiesInfo;
import com.hao.tool.util.util.FileBlankUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.List;

/**
 * description
 *
 * @author RuiHaoZ on GZ.cmhk
 * @date 2019-11-22 21:46
 */
@Controller
@RequestMapping("/text")
public class TextInfoController {

    @Autowired
    private PropertiesInfo propertiesInfo;

    private Logger logger = LoggerFactory.getLogger(TextInfoController.class);


    @GetMapping("{code}")
    public ModelAndView add(@PathVariable String code) throws Exception {
        ModelAndView mv = new ModelAndView("text/sync");
        mv.addObject("textCode", code);
        return mv;
    }

    @GetMapping("/running")
    public ModelAndView running() {
        ModelAndView mv = new ModelAndView("text/running");
        return mv;
    }

    /**
     * 查看文本文件信息
     * 默认查看配置文件配置路径
     *
     * @param response    响应
     * @param absFilePath 绝对路径
     * @param sl          开始行数
     * @param el          结束行数
     * @throws Exception
     */
    @GetMapping("/file")
    public void log(HttpServletResponse response, String absFilePath,
                    Integer sl, Integer el) throws Exception {

        String filePath = propertiesInfo.getLocalLogFilePath();

        File thisFile = FileBlankUtil.buildAndFileIsExist(filePath, absFilePath);
        FileBlankUtil.fileSizeIsBig(thisFile, Commons.SIZE_MB * 32);

        logger.info("查看文本文件「{}」", filePath);
        String fileType = FileUtil.getType(thisFile);
        if (!fileType.equalsIgnoreCase("log")
                && !fileType.equalsIgnoreCase("txt")) {
            throw new Exception("此类文件不能直接查看，请使用 /file/down?absFilePath=" + absFilePath + " 下载");
        }
        try (OutputStream outputStream = response.getOutputStream()) {
            if (sl != null) {
                int startLine = 0;
                int endLine = 0;
                List<String> fileLine = FileUtil.readLines(thisFile, Charset.defaultCharset());
                Integer fileLineCount = fileLine.size();
                if (Math.abs(sl) < fileLineCount) {
                    if (sl > 0) {
                        endLine = sl;
                    } else {
                        startLine = fileLineCount + sl;
                        endLine = fileLineCount;
                    }
                } else {
                    endLine = fileLineCount;
                }
                List<String> outStrList = fileLine.subList(startLine, endLine);
                for (String s : outStrList) {
                    outputStream.write((s + "\n").getBytes());
                }
            } else {
                byte[] bytes = FileUtil.readBytes(thisFile);
                outputStream.write(bytes);
            }

        } catch (Exception e) {
            throw new Exception("读取文件出错");
        }
    }

}
